package com.cloud.bssp.chinesenewyear.grabredenvelope.service.impl;

import com.cloud.bssp.chinesenewyear.grabredenvelope.GlobalDataCache;
import com.cloud.bssp.chinesenewyear.grabredenvelope.GlobalInitProcessor;
import com.cloud.bssp.chinesenewyear.grabredenvelope.entity.PeopleDO;
import com.cloud.bssp.chinesenewyear.grabredenvelope.entity.RedEnvelopeDO;
import com.cloud.bssp.chinesenewyear.grabredenvelope.service.ISendRedEnvelopeService;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @description： 发红包接口
 * @author：weirx
 * @date：2022/1/6 9:56
 * @version：3.0
 */
public class SendRedEnvelopeServiceImpl implements ISendRedEnvelopeService {

    @Override
    public RedEnvelopeDO send(RedEnvelopeDO redEnvelopeDO) throws Exception {
        // 获取全局变量
        GlobalDataCache globalDataCache = GlobalInitProcessor.getGlobalDataCache();

        //获取用户信息
        PeopleDO peopleDO = globalDataCache.getPeopleCache().get(redEnvelopeDO.getPeopleId());
        //校验用户金额是否足够发红包
        if (peopleDO.getAmount().compareTo(redEnvelopeDO.getAmount()) < 0) {
            // 直接跑出异常，调用时捕获异常内容，实际应该定制通用返回结果，并且有对象的成功失败标识
            throw new Exception("您当前余额不足，红包发送失败");
        }
        // 扣除用户账户金额
        BigDecimal subtract = peopleDO.getAmount().subtract(redEnvelopeDO.getAmount());
        peopleDO.setAmount(subtract);
        // 将用户存入缓存当中
        Map<Integer, PeopleDO> peopleCache = globalDataCache.getPeopleCache();
        peopleCache.put(peopleDO.getId(), peopleDO);
        globalDataCache.setPeopleCache(peopleCache);
        // 获取全局唯一红包id，并将红包存入缓存
        redEnvelopeDO.setId(globalDataCache.getId());
        Map<Integer, RedEnvelopeDO> redEnvelopeCache = globalDataCache.getRedEnvelopeCache();
        redEnvelopeCache.put(redEnvelopeDO.getId(), redEnvelopeDO);
        globalDataCache.setRedEnvelopeCache(redEnvelopeCache);
        return redEnvelopeDO;
    }
}
